package org.cardoso.coyote.persistence;

import java.io.Serializable;
import java.util.Collection;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceException;

import org.cardoso.coyote.persistence.filter.QueryFilter;

public class PersistenceDefault<T extends EntityBean> extends AbstractPersistence<T> implements Serializable, Persistence<T> {

	private static final long serialVersionUID = 1L;
	
	public PersistenceDefault() {
		super();
	}

	@SuppressWarnings("rawtypes")
	public PersistenceDefault(Class entityClass) {
		super(entityClass);
	}

	@PersistenceContext
	public void setEntityManager(EntityManager entityManager) {
		this.entityManager = entityManager;
	}

	@Override
	public void save(T entity) {
		try {
			this.entityManager.merge(entity);
		} catch (Exception e) {
			throw new PersistenceException(e);
		}
	}

	@Override
	public void remove(T entity) {
		try {
			T entityBean = (T) getEntity(((EntityBean) entity).getId());
			if (entityBean != null)
				this.entityManager.remove(entityBean);
		} catch (Exception e) {
			throw new PersistenceException(e);
		}
	}

	@Override
	public T getEntity(Long id) {
		return (T) this.getEntity(entityClass, id);
	}

	@SuppressWarnings("rawtypes")
	@Override
	public T getEntity(Class entityClass, Long id) {
		return (T) super.getEntity(entityClass, id);
	}

	@Override
	public Long count() {
		return super.count();
	}

	@Override
	public Collection<T> find() {
		return super.find();
	}

	@Override
	public Long count(QueryFilter queryFilter) {
		return super.count(queryFilter);
	}

	@Override
	public List<T> find(QueryFilter queryFilter) {
		return super.find(queryFilter);
	}
}